package com.example.ordersystem.controller;

import com.example.ordersystem.entity.CartItem;
import com.example.ordersystem.entity.Dish;
import com.example.ordersystem.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.example.ordersystem.service.OrderService;
@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private DishService dishService;

    @Autowired
    private OrderService orderService;

    @GetMapping
    public String viewCart(Model model, HttpSession session) {
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        if (cart == null) cart = new ArrayList<>();
        model.addAttribute("cart", cart);
        double total = cart.stream().mapToDouble(item -> item.getPrice() * item.getQuantity()).sum();
        model.addAttribute("total", total);
        return "cart";
    }

    @PostMapping("/add")
    public String addToCart(@RequestParam Long dishId, @RequestParam Integer quantity, HttpSession session) {
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        if (cart == null) cart = new ArrayList<>();
        Dish dish = dishService.getDishById(dishId);
        if (dish != null) {
            boolean found = false;
            for (CartItem item : cart) {
                if (item.getDishId().equals(dishId)) {
                    item.setQuantity(item.getQuantity() + quantity);
                    found = true;
                    break;
                }
            }
            if (!found) {
                CartItem item = new CartItem();
                item.setDishId(dish.getId());
                item.setDishName(dish.getName());
                item.setPrice(dish.getPrice());
                item.setQuantity(quantity);
                item.setImageUrl(dish.getImageUrl());
                cart.add(item);
            }
        }
        session.setAttribute("cart", cart);
        return "redirect:/cart";
    }

    @PostMapping("/remove")
    public String removeFromCart(@RequestParam Long dishId, HttpSession session) {
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        if (cart != null) {
            Iterator<CartItem> it = cart.iterator();
            while (it.hasNext()) {
                if (it.next().getDishId().equals(dishId)) {
                    it.remove();
                    break;
                }
            }
        }
        session.setAttribute("cart", cart);
        return "redirect:/cart";
    }

    @PostMapping("/clear")
    public String clearCart(HttpSession session) {
        session.removeAttribute("cart");
        return "redirect:/cart";
    }

    @GetMapping("/checkout")
    public String checkoutPage(Model model, HttpSession session) {
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        if (cart == null) cart = new ArrayList<>();
        model.addAttribute("cart", cart);
        double total = cart.stream().mapToDouble(item -> item.getPrice() * item.getQuantity()).sum();
        model.addAttribute("total", total);
        return "checkout";
    }

    @PostMapping("/checkout")
    public String doCheckout(@RequestParam String customerName,
                            @RequestParam String customerPhone,
                            @RequestParam String address,
                            @RequestParam String payType,
                            HttpSession session,
                            Model model) {
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        if (cart == null || cart.isEmpty()) return "redirect:/cart";
        // 先校验所有菜品库存
        for (CartItem item : cart) {
            Dish dish = dishService.getDishById(item.getDishId());
            if (dish.getStock() == null || dish.getStock() < item.getQuantity()) {
                model.addAttribute("error", "菜品【" + dish.getName() + "】库存不足，无法下单！");
                model.addAttribute("cart", cart);
                double total = cart.stream().mapToDouble(i -> i.getPrice() * i.getQuantity()).sum();
                model.addAttribute("total", total);
                return "checkout";
            }
        }
        // 扣减库存并保存订单
        for (CartItem item : cart) {
            Dish dish = dishService.getDishById(item.getDishId());
            dish.setStock(dish.getStock() - item.getQuantity());
            dishService.saveDish(dish);
            com.example.ordersystem.entity.Order order = new com.example.ordersystem.entity.Order();
            order.setDish(new com.example.ordersystem.entity.Dish());
            order.getDish().setId(item.getDishId());
            order.setQuantity(item.getQuantity());
            order.setTotalPrice(item.getPrice() * item.getQuantity());
            order.setCustomerName(customerName);
            order.setCustomerPhone(customerPhone);
            order.setAddress(address);
            order.setStatus("PAID");
            order.setDescription("支付方式：" + payType);
            orderService.createOrder(order);
        }
        session.removeAttribute("cart");
        return "redirect:/orders";
    }
} 